# !/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
@作者 杨阳
@时间 2018-07-24
@说明 生成代码功能的数据库工具类
@注意事项
"""
from util.generation.generationutil import GenerationConstant
import pymysql.cursors


def get_table_columns(table_name):
    """
    根据表名查询出表中的所有列
    :param table_name:      表名
    :return:                列集合
    """
    # 连接MySQL数据库
    connection = pymysql.connect(host=GenerationConstant.db_host,
                                 port=GenerationConstant.db_port,
                                 user=GenerationConstant.db_user,
                                 password=GenerationConstant.db_pwd,
                                 db=GenerationConstant.db_database,
                                 charset='utf8mb4',
                                 cursorclass=pymysql.cursors.DictCursor)

    # 通过cursor创建游标
    cursor = connection.cursor()
    sql = '''
        SELECT
            COLUMN_NAME,
            DATA_TYPE,
            IFNULL(CHARACTER_MAXIMUM_LENGTH,NUMERIC_PRECISION) CHARACTER_MAXIMUM_LENGTH,
            COLUMN_COMMENT,
            IS_NULLABLE
        FROM
            information_schema.COLUMNS
        WHERE
            table_name = '{}'
        AND TABLE_SCHEMA = '{}'
    '''.format(table_name, GenerationConstant.db_database)
    cursor.execute(sql)
    result = cursor.fetchall()
    # {'COLUMN_NAME': 'id', 'DATA_TYPE': 'char', 'CHARACTER_MAXIMUM_LENGTH': 36, 'COLUMN_COMMENT': '用户ID'}
    return result


def get_database_tables():
    """
    查询库中的所有表
    :return:
    """
    # 连接MySQL数据库
    connection = pymysql.connect(host=GenerationConstant.db_host,
                                 port=GenerationConstant.db_port,
                                 user=GenerationConstant.db_user,
                                 password=GenerationConstant.db_pwd,
                                 db=GenerationConstant.db_database,
                                 charset='utf8mb4',
                                 cursorclass=pymysql.cursors.DictCursor)

    # 通过cursor创建游标
    cursor = connection.cursor()
    select_table_sql = '''
        SELECT TABLE_NAME
            FROM INFORMATION_SCHEMA.TABLES
                WHERE TABLE_SCHEMA = '{}'
            AND TABLE_TYPE = 'base table'
    '''.format(GenerationConstant.db_database)
    cursor.execute(select_table_sql)
    result = cursor.fetchall()
    list = []
    for data in result:
        table_name = data["TABLE_NAME"]
        # print("表名：{}".format(table_name))
        model_name = generating_entity_class_names(table_name)
        # print("实体类名称:{}".format(new_table_name))
        list.append({
            'table_name': table_name,
            'model_name': model_name
        })
    connection.close()
    return list


def generating_entity_class_names(table_name):
    """
    根据表名生成实体类名称，
    生成规则：
    1. 合用下划线分隔字符串
    2. 分隔后的每个字符串首字母大写
    3. 将分隔后的字符串首字母大写后拼在一起，再拼上Model
    4. 例：t_user 生成后为 TUserModel
    :return: db.Model
    """
    new_name = []
    for name in table_name.split("_"):
        n_name = name[0].upper() + name[1:]
        new_name.append(n_name)

    return ''.join(new_name) + "Model"
